package com.smartfast4j.manager.modules.sys.service.impl;

import com.smartfast4j.common.component.cache.annotation.Cache;
import com.smartfast4j.common.config.Cachekey;
import com.smartfast4j.manager.common.bean.CnAreaVo;
import com.smartfast4j.manager.common.bean.JsTree;
import com.smartfast4j.manager.common.bean.JsTreeState;
import com.smartfast4j.manager.common.bean.ZtreeAreaVo;
import com.smartfast4j.manager.modules.sys.service.SysCnAreaService;
import com.smartfast4j.mapper.sys.SysCnAreaMapper;
import com.smartfast4j.pojo.sys.SysCnArea;
import com.smartfast4j.pojo.sys.SysCnAreaExample;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysCnAreaServiceImpl implements SysCnAreaService {
    @Autowired
    private SysCnAreaMapper sysCnAreaMapper;

    private static final Logger logger = LoggerFactory.getLogger(SysCnAreaServiceImpl.class);

    public int countByExample(SysCnAreaExample example) {
        int count = this.sysCnAreaMapper.countByExample(example);
        logger.debug("count: {}", count);
        return count;
    }

    public SysCnArea selectByPrimaryKey(Long id) {
        return this.sysCnAreaMapper.selectByPrimaryKey(id);
    }

    public List<SysCnArea> selectByExample(SysCnAreaExample example) {
        return this.sysCnAreaMapper.selectByExample(example);
    }

    public int deleteByPrimaryKey(Long id) {
        return this.sysCnAreaMapper.deleteByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(SysCnArea record) {
        return this.sysCnAreaMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(SysCnArea record) {
        return this.sysCnAreaMapper.updateByPrimaryKey(record);
    }

    public int deleteByExample(SysCnAreaExample example) {
        return this.sysCnAreaMapper.deleteByExample(example);
    }

    public int updateByExampleSelective(SysCnArea record, SysCnAreaExample example) {
        return this.sysCnAreaMapper.updateByExampleSelective(record, example);
    }

    public int updateByExample(SysCnArea record, SysCnAreaExample example) {
        return this.sysCnAreaMapper.updateByExample(record, example);
    }

    public int insert(SysCnArea record) {
        return this.sysCnAreaMapper.insert(record);
    }

    public int insertSelective(SysCnArea record) {
        return this.sysCnAreaMapper.insertSelective(record);
    }

    public int insertBatchSelective(List<SysCnArea> records) {
        return this.sysCnAreaMapper.insertBatchSelective(records);
    }

    public int updateBatchByPrimaryKeySelective(List<SysCnArea> records) {
        return this.sysCnAreaMapper.updateBatchByPrimaryKeySelective(records);
    }

    @Cache(key = "'" + Cachekey.Sys.AREA+ "' + #id") //缓存获取到的CnAreaVo信息
    @Override
    public CnAreaVo getAreaTreeById(Long id) {
        //根据Id获取区域信息
        SysCnArea area = selectByPrimaryKey(id);
        //获取这个id下的子子孙孙区域信息
        CnAreaVo areaVo = new CnAreaVo();
        try {
            //相同属性复制
            BeanUtils.copyProperties(areaVo,area);
            //递归查询(效率慢)
            recursionQuerySubArea(areaVo);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return areaVo;
    }

    @Override
    public List<JsTree> loadAreaJsTree(String id) {
        List<JsTree> jsTreeList = new ArrayList<>();
        SysCnAreaExample example = new SysCnAreaExample();
        if(StringUtils.isNotEmpty(id) && !"#".equals(id)){
            //加载指定Id下的子区域
            example.createCriteria().andParentIdEqualTo(Long.parseLong(id));
        }else {
            example.createCriteria().andLevelEqualTo((short)1);//加载一级行政区域
        }
        List<SysCnArea> cnAreaList = selectByExample(example);
        if(CollectionUtils.isNotEmpty(cnAreaList)){
            cnAreaList.forEach(cnArea -> {
                //组织jsTree树形控件所需要的数据格式
                JsTree jsTree = new JsTree();
                jsTree.setId(cnArea.getId().toString());
                jsTree.setText(cnArea.getName());
                JsTreeState state = new JsTreeState();
                state.setDisabled(false);
                state.setOpened(false);
                state.setSelected(false);
                jsTree.setState(state);
                // 递归子节点
                jsTree.setChildren(true);
                jsTreeList.add(jsTree);
            });
        }
        return jsTreeList;
    }

    @Override
    public List<ZtreeAreaVo> loadAreaZtree(String id) {
        List<ZtreeAreaVo> treeList = new ArrayList<>();
        SysCnAreaExample example = new SysCnAreaExample();
        if(StringUtils.isNotEmpty(id)){
            //加载指定Id下的子区域
            example.createCriteria().andParentIdEqualTo(Long.parseLong(id));
        }else {
            example.createCriteria().andLevelEqualTo((short)1);//加载一级行政区域
        }
        List<SysCnArea> cnAreaList = selectByExample(example);
        if(CollectionUtils.isNotEmpty(cnAreaList)){
            cnAreaList.forEach(cnArea -> {
                //组织zTree树形控件所需要的数据格式
                ZtreeAreaVo ztreeAreaVo = new ZtreeAreaVo();
                ztreeAreaVo.setId(cnArea.getId().toString());
                ztreeAreaVo.setpId(cnArea.getParentId().toString());
                ztreeAreaVo.setName(cnArea.getName());
                ztreeAreaVo.setNodeLevel(Integer.parseInt(cnArea.getLevel().toString()));
                treeList.add(ztreeAreaVo);
            });
        }
        return treeList;
    }

    /**
     * 递归查询子区域
     */
    private void recursionQuerySubArea(CnAreaVo areaVo){
        if(areaVo.getParentId() != null){
            areaVo.setParentName(selectByPrimaryKey(areaVo.getParentId()).getName());
            SysCnAreaExample example = new SysCnAreaExample();
            example.createCriteria().andParentIdEqualTo(areaVo.getId());
            List<CnAreaVo> childrenAreaVoList = new ArrayList<>();
            //查找子区域信息
            List<SysCnArea> subAreaList = selectByExample(example);
            if(CollectionUtils.isNotEmpty(subAreaList)){
                //子节点信息不为空
                for(SysCnArea area:subAreaList){
                    CnAreaVo tmpAreaVo = new CnAreaVo();
                    try {
                        BeanUtils.copyProperties(tmpAreaVo,area);
                        childrenAreaVoList.add(tmpAreaVo);
                    }  catch (Exception e) {
                        logger.error(e.getMessage(),e);
                    }
                }
                for(CnAreaVo tmpAreaVo:childrenAreaVoList){
                    //递归查询
                    recursionQuerySubArea(tmpAreaVo);
                }
            }
            areaVo.setChildrenList(childrenAreaVoList);
        }
    }
}